package hjt.com.module_test.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PointF;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import androidx.annotation.Nullable;

public class BezierTwo extends View {

    private Paint paint;
    private PointF start;
    private PointF end;
    private PointF controler;
    private int centerX;
    private int centerY;

    public BezierTwo(Context context) {
        this(context, null);
    }

    public BezierTwo(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        paint = new Paint();
        paint.setColor(Color.RED);
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(8);

        start = new PointF(0, 0);
        end = new PointF(0, 0);
        controler = new PointF(0, 0);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        centerX = w / 2;
        centerY = h / 2;
        start.x = centerX - 400;
        start.y = centerY;

        end.x = centerX + 400;
        end.y = centerY;

        controler.x = centerX;
        controler.y = centerY - 100;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        controler.x = event.getX();
        controler.y = event.getY();
        invalidate();
        return true;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        paint.setColor(Color.GRAY);
        paint.setStyle(Paint.Style.FILL);
        canvas.drawCircle(start.x, start.y, 10, paint);
        canvas.drawCircle(end.x, end.y, 10, paint);
        canvas.drawCircle(controler.x, controler.y, 10, paint);

        paint.setStyle(Paint.Style.STROKE);

        canvas.drawLine(start.x, start.y, controler.x, controler.y, paint);
        canvas.drawLine(end.x, end.y, controler.x, controler.y, paint);

        paint.setColor(Color.RED);

        Path path = new Path();
        path.moveTo(start.x, start.y);
        path.quadTo(controler.x, controler.y, end.x, end.y);
        canvas.drawPath(path,paint);

    }
}
